package com.easemob.helpdesk.widget.chatrow;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.helpdesk.adapter.UserChatAdapter;
import com.easemob.helpdesk.bean.MsgChat;
import com.easemob.helpdesk.recorder.MediaManager;
import com.easemob.helpdesk.utils.DownloadManager;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.utils.HDLog;

import java.io.File;

import okhttp3.Request;

/**
 * Created by wsj on 2018/5/22.
 */

public class MsgVoiceViewHolder extends BaseMsgViewHolder{

    public View lengthView;
    public TextView tvLength;
    public ProgressBar pb;
    public ImageView ivStatus;
    public TextView tvNick;
    public ImageView ivReadStatus;

    public MsgVoiceViewHolder(Activity activity, UserChatAdapter chatAdapter, View itemView) {
        super(activity, chatAdapter, itemView);
    }

    @Override
    public void handleViewMessage(MsgChat message, int position) {
        final MsgChat voiceBody = message;

        if (voiceBody == null) {
            return;
        }
        int len = 0; //voiceBody.getVoiceLength();

        if(len < 0 || len == 100) {
            len = 0;
        }

        if (len > 0) {
            tvLength.setText(len + "\"");
            tvLength.setVisibility(View.VISIBLE);
        } else {
            tvLength.setVisibility(View.INVISIBLE);
        }

        ViewGroup.LayoutParams layoutParams = lengthView.getLayoutParams();
        layoutParams.width = (int) (adapter.mMinItemWidth + Math.min(adapter.mMaxItemWidth / 60f * len, adapter.mMaxItemWidth));


        final boolean isSend = (message.getDirect().equals("HX"));
        if (!isSend) {
            HDLog.d(TAG, "it is receive msg");
            if (!TextUtils.isEmpty(voiceBody.getMsgId())) {
                File file = new File(DownloadManager.getResourcePath(message.getId() + message.getType()));
                if (!file.exists()) {
                    downloadVoiceFile(message);
                }
            }

            ivReadStatus.setVisibility(View.GONE);

//            if (message.isListened()) {
//                ivReadStatus.setVisibility(View.GONE);
//            } else {
//                ivReadStatus.setVisibility(View.VISIBLE);
//            }
        }

        lengthView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickVoiceItem(v, isSend, voiceBody);
            }
        });

//        if (isSend) {
//            setMessageSendCallback(message);
//        }else{
//            setMessageReceiveCallback(message);
//        }

        pb.setVisibility(View.GONE);
        if (ivStatus != null) {
            ivStatus.setVisibility(View.GONE);
        }

//        switch (message.getStatus()) {
//            case SUCCESS:
//                pb.setVisibility(View.GONE);
//                if (ivStatus != null) {
//                    ivStatus.setVisibility(View.GONE);
//                }
//                break;
//            case FAIL:
//                if (pb != null) {
//                    pb.setVisibility(View.GONE);
//                }
//                if (ivStatus != null) {
//                    ivStatus.setVisibility(View.VISIBLE);
//                }
//                break;
//            case INPROGRESS:
//                if (pb != null) {
//                    pb.setVisibility(View.VISIBLE);
//                }
//                break;
//            case CREATE:
//                if (pb != null){
//                    pb.setVisibility(View.GONE);
//                }
//                if (ivStatus != null){
//                    ivStatus.setVisibility(View.VISIBLE);
//                }
//                break;
//        }
    }

    @Override
    protected void onFindViewById() {
        lengthView = findViewById(R.id.id_recorder_length);
        tvLength = findViewById(R.id.tv_length);
        pb = findViewById(R.id.pb_sending);
        ivStatus = findViewById(R.id.msg_status);
        tvNick = findViewById(R.id.tv_userid);
        ivReadStatus = findViewById(R.id.iv_unread_voice);
    }

    private void downloadVoiceFile(final MsgChat message) {

        DownloadManager.downloadFile(message.getUrl(), message.getId() + message.getType(), new DownloadManager.ResultCallback() {
            @Override
            public void onError(Request request, Exception e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.refresh();
                    }
                });
            }

            @Override
            public void onResponse(Object response) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.refresh();
                    }
                });
            }

            @Override
            public void onProgress(double total, double current) {

            }
        });

//        if (message.getMessageCallback() != null) {
//            message.setMessageCallback(new HDDataCallBack() {
//                @Override
//                public void onSuccess(Object value) {
//                    activity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            adapter.refresh();
//                        }
//                    });
//                }
//
//                @Override
//                public void onError(int error, String errorMsg) {
//                    activity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            adapter.refresh();
//                        }
//                    });
//                }
//            });
//        }
//        HDClient.getInstance().chatManager().downloadAttachment(message);
    }

    private void clickVoiceItem(View v, final boolean isSend, final MsgChat message) {
        File file = new File(DownloadManager.getResourcePath(message.getId() + message.getType()));
        if (file.exists() && file.isFile()) {
            playVoiceItem(v, isSend, message);
        } else {
            DownloadManager.downloadFile(message.getUrl(), message.getId() + message.getType(), new DownloadManager.ResultCallback() {
                @Override
                public void onError(Request request, Exception e) {
                    activity.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(activity, "语音下载失败！", Toast.LENGTH_SHORT).show();
                            adapter.refresh();
                        }
                    });
                }

                @Override
                public void onResponse(Object response) {
                    activity.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            adapter.refresh();
                        }
                    });
                }

                @Override
                public void onProgress(double total, double current) {

                }
            });

//            if (message.getStatus() == HDMessage.Status.SUCCESS || message.getStatus() == HDMessage.Status.FAIL) {
//
//                if (message.getMessageCallback() == null) {
//                    message.setMessageCallback(new HDDataCallBack() {
//                        @Override
//                        public void onSuccess(Object value) {
//                            activity.runOnUiThread(new Runnable() {
//
//                                @Override
//                                public void run() {
//                                    adapter.refresh();
//                                }
//                            });
//                        }
//
//                        @Override
//                        public void onError(int error, String errorMsg) {
//                            activity.runOnUiThread(new Runnable() {
//
//                                @Override
//                                public void run() {
//                                    Toast.makeText(activity, "语音下载失败！", Toast.LENGTH_SHORT).show();
//                                    adapter.refresh();
//                                }
//                            });
//                        }
//                    });
//                }
//                Toast.makeText(activity, "正在下载请稍后...", Toast.LENGTH_SHORT).show();
//                HDClient.getInstance().chatManager().downloadAttachment(message);
//                HDLog.e(TAG, "file not exist");
//            }


        }

    }


    private void playVoiceItem(View v, final boolean isSend, MsgChat message) {
        View animView = v.findViewById(R.id.id_recorder_anim);

        //播放动画
        if (adapter.animView != null) {
            if (adapter.animStatus == 0) {
                adapter.animView.setBackgroundResource(R.drawable.icon_audio_blue_3);
            } else if (adapter.animStatus == 1){
                adapter.animView.setBackgroundResource(R.drawable.icon_audio_white_3);
            } else {
                HDLog.e(TAG, "anim play abnormal");
            }
            if (animView == adapter.animView) {
                MediaManager.release();
                adapter.animView = null;
                adapter.animStatus = -1;
                return;
            }
        }

        adapter.animView = animView;
        if (isSend) {
            adapter.animView.setBackgroundResource(R.drawable.voice_to_icon);
            adapter.animStatus = 0;
        } else {
            adapter.animView.setBackgroundResource(R.drawable.voice_from_icon);
            adapter.animStatus = 1;
            ivReadStatus.setVisibility(View.GONE);

//            if (!message.isListened()) {

//                message.setListened(true);
//                HDClient.getInstance().chatManager().setMessageListened(message);

//            }
        }
        final AnimationDrawable anim = (AnimationDrawable) adapter.animView.getBackground();
        anim.start();

        //播放音频
        MediaManager.playSound(activity, DownloadManager.getResourcePath(message.getId() + message.getType()), new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (isSend) {
                    adapter.animView.setBackgroundResource(R.drawable.icon_audio_blue_3);
                } else {
                    adapter.animView.setBackgroundResource(R.drawable.icon_audio_white_3);
                }
                adapter.animStatus = -1;
            }
        });

    }
}
